package com.gitee.elf.core.entity

import com.gitee.elf.api.common.MetaWatcher
import com.gitee.elf.core.data.Data
import com.gitee.elf.util.getMethodsByPrefix
import taboolib.library.reflex.Reflex.Companion.invokeMethod

abstract class AbstractProxyEntity<T>(val instance: EntityInstance) : ProxyEntity<T> {


    val metas = instance.metadataContainer

    val theme = instance.theme

    val status = instance.status

    val fields = mutableMapOf<String, MetaWatcher<Data>>()

    // 初始化字段
    @Suppress("UNCHECKED_CAST")
    override fun onSpawn() {
        this::class.java.declaredFields.forEach {
            if (MetaWatcher::class.java.isAssignableFrom(it.type)) {
                val metaWatcher = it.get(this) as MetaWatcher<Data>
                fields[metaWatcher.name] = metaWatcher
            }
        }
        fields.forEach { it.value.onUpdate(it.value.get()) }
    }

    override fun onUpdate(id: String, data: MetadataContainer.Data) {
        val watcher = fields[id] ?: return
        watcher.set(data.bind)
    }


}